package com.msb.mall.product.service.impl;

import com.msb.common.dto.SkuReductionDTO;
import com.msb.common.dto.es.SkuESModel;
import com.msb.mall.product.entity.*;
import com.msb.mall.product.feign.CouponFeignService;
import com.msb.mall.product.service.*;
import com.msb.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品的上架发布信息
     *
     * @param spuInfoVO
     */
    @Transactional
    @Override
    public void saveSpuInfoVo(SpuInfoVO spuInfoVO) {
        //1.保存商品的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO, spuInfoEntity);
        //更新创建时间 和 更新时间
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2.保存详情信息 pms_spu_info_desc
        List<String> decripts = spuInfoVO.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.save(descEntity);
        //3.保存spu 的图片信息  pms_spu_images
        List<String> images = spuInfoVO.getImages();
        List<SpuImagesEntity> imagesEntities = images
                .stream()
                .map(item -> {
                    SpuImagesEntity entity = new SpuImagesEntity();
                    entity.setSpuId(spuInfoEntity.getId());
                    entity.setImgUrl(item);
                    return entity;
                })
                .collect(Collectors.toList());
        spuImagesService.saveBatch(imagesEntities);

        //4.保存规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        //对规格数据做对应的处理
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuInfoEntity.getId());
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
//            AttrResponseVO attrInfo =attrService.getAttrInfo(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());

            return valueEntity;
        })
                .collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //5.保存当前的spu 对应的所有的SKU信息
        List<Skus> skus = spuInfoVO.getSkus();
        //5.1 保存 sku 的基本信息 pms_sku_info
        if (skus != null && skus.size() > 0) {
            skus.forEach((item) -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(skuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> images1 = item.getImages();
                String defaultImage = "";
                for (Images images2 : images1) {
                    if (images2.getDefaultImg() == 1) {
                        defaultImage = images2.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.save(skuInfoEntity);

                //5.2 保存 sku 图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map(img -> {
                    SkuImagesEntity entity = new SkuImagesEntity();
                    entity.setSkuId(skuInfoEntity.getSkuId());
                    entity.setImgUrl(img.getImgUrl());
                    entity.setDefaultImg(img.getDefaultImg());
                    return entity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                //5.3 保存 满减 折扣 信息 mall_sms sms_sku_ladder sms_full_reduction sms_member_price
                SkuReductionDTO dto = new SkuReductionDTO();
                BeanUtils.copyProperties(item, dto);
                dto.setSkuId(skuInfoEntity.getSkuId());
                couponFeignService.saveFullReductionInfo(dto);

                //5.4 sku 的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(sale -> {
                    SkuSaleAttrValueEntity entity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sale, entity);
                    return entity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
            });

        }


        //6.设置金币成长值  mall-sms  sms_spu_bounds

    }

    /**
     * 实现商品上架 -》 商品相关数据存储到elasticSearch 中
     * 1、根据spuId 查询出相关的信息
     * 封装到对应的对象中
     * 2、将封装数据存储到elasticSearch 中- 》 调用远程 mall-search
     * 3、更新spuId 对应的状态 上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //1、根据spuId 查询出相关的信息，封装到SkuESModel 对象中
        List<SkuESModel> skuEs =new ArrayList<>();
        //查询规格参数信息 根据spuId

        //1。product_attr_value

        //2、 attr search_type 决定该属性是否支持检索


        //2、将封装数据存储到elasticSearch 中- 》 调用远程 mall-search，将SkuESModel 存储到es中
        List<SkuInfoEntity> skus =skuInfoService.getSkusBySpuId(spuId);
        List<SkuESModel> skuESModels = skus.stream().map((item) -> {
            SkuESModel model = new SkuESModel();
            //先实现属性复制
            BeanUtils.copyProperties(item,model);
            model.setSubTitle(item.getSkuTitle());
            model.setSkuPrice(item.getPrice());

            //是否有库存 - 》 去库存系统查询

            //hotScore 热度分 默认为0
            model.setHotScore(0l);
            //品牌和类别的名称
            BrandEntity brand = brandService.getById(item.getBrandId());
            CategoryEntity categroy = categoryService.getById(item.getCatalogId());
            model.setBrandName(brand.getName());
            model.setBrandId(brand.getBrandId());
            model.setCatalogName(categroy.getName());
            //对应的规格参数

            return model;
        }).collect(Collectors.toList());
        //3、更新spuId 对应的状态 上架
    }

}
